package controller

import (
	"StrayAnimals/internal/model"
	"StrayAnimals/internal/service"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
)

func AdoptAnimal(c *gin.Context) {
	var userInput struct {
		AnimalId  string `json:"animalId"`
		AdopterId string `json:"adopterId"`
		AdoptAt   string `json:"adoptAt"`
	}

	if err := c.ShouldBindJSON(&userInput); err != nil {
		c.JSON(400, gin.H{
			"code":    400,
			"message": "请求参数错误；" + err.Error(),
		})
		return
	}

	animal, err := service.GetAnimalById(userInput.AnimalId)
	if err != nil {
		c.JSON(400, gin.H{
			"code":    400,
			"message": "数据库中没有该动物" + err.Error(),
		})
		return
	}

	newAdoption := model.Adoption{
		ID:         uuid.New().String(),
		AnimalID:   userInput.AnimalId,
		AdopterID:  userInput.AdopterId,
		AdoptionAt: userInput.AdoptAt,
	}

	if err := service.CreateNewAdoption(newAdoption); err != nil {
		c.JSON(500, gin.H{
			"code":    501,
			"message": "系统错误，领养动物失败，请稍后再试；" + err.Error(),
		})
		return
	}

	// 更新动物领养状态
	animal.IsAdopted = true

	// 将更新后的动物领养状态保存到数据库
	if err := service.UpdateAnimal(animal); err != nil {
		c.JSON(500, gin.H{
			"code":    501,
			"message": "系统错误，领养动物失败，请稍后再试；" + err.Error(),
		})
		return
	}

	c.JSON(200, gin.H{
		"code":    200,
		"message": "领养动物成功",
	})
}
